import { NextResponse } from "next/server";
import generateCode from "@/lib/code-generate";
import { setCode, getMailInfo } from "@/lib/code-cache";
import sendMail from "@/lib/mailer";
import isEmail from "@/lib/isemail";
import html from "@/lib/mail-html";

export async function POST(req) {
  const { email } = await req.json();
  if (!email) { return new Response(JSON.stringify({ message: "邮箱不能为空", code: 1 }), { status: 400 }); }
  if (!isEmail(email)) { return new Response(JSON.stringify({ message: "邮箱格式不正确", code: 1 }), { status: 400 }); }
  const codeInfo = getMailInfo(email);
  if (codeInfo && (Date.now() - codeInfo.createdAt < 60 * 1000)) { return NextResponse.json({ message: "验证码已发送，请稍后再试", code: 1 }); }
  const code = generateCode(6);
  setCode(email, code);
  try {
    await sendMail({ to: email, subject: "登录验证码", html: html(code) });
    return NextResponse.json({ message: "发送成功", code: 0 });
  } catch (err) {
    console.error("邮件发送失败:", err);
    return NextResponse.json({ message: "发送失败", code: 1 }, { status: 500 });
  }
}
